package com.ejlchina.common.oss;




public abstract class AbstractOssManager implements OssManager {

	
	protected String endpoint;
	
	protected Long maxSize = (long) (300000 * 1024);
	
	
	protected String resolveFileAccessUrl(String fileKey) {
		return getBaseUrl() + fileKey;
	}
	
	protected String resolveFileKey(String fileAccessUrl) {
		if (fileAccessUrl != null) {
			String baseUrl = getBaseUrl();
			if (fileAccessUrl.startsWith(baseUrl)) {
				return fileAccessUrl.substring(baseUrl.length());
			}
		}
		return null;
	}
	
	protected String getBaseUrl() {
		String protocol = "http://";
		String host = endpoint;
		if (endpoint.startsWith("http://")) {
			host = host.substring(7);
		} else if (endpoint.startsWith("https://")) {
			host = host.substring(8);
			protocol = "https://";
		}
		if (host.endsWith("/")) {
			host = host.substring(0, host.length() - 1);
		}
		return getBaseAccessUrl(protocol, host);
	}
	
	protected abstract String getBaseAccessUrl(String protocol, String host);
	
	
	protected String getContentType(String fileExtension){
		if (fileExtension != null) {
			String lowerCase = fileExtension.toLowerCase();
			if(".bmp".equals(lowerCase)) return "image/bmp";
			if(".gif".equals(lowerCase)) return "image/gif";
			if(".jpeg".equals(lowerCase) || "jpg".equals(lowerCase)  || "png".equals(lowerCase) ) return "image/jpeg";
			if(".html".equals(lowerCase)) return "text/html";
			if(".txt".equals(lowerCase)) return "text/plain";
			if(".vsd".equals(lowerCase)) return "application/vnd.visio";
			if(".ppt".equals(lowerCase) || "pptx".equals(lowerCase)) return "application/vnd.ms-powerpoint";
			if(".doc".equals(lowerCase) || "docx".equals(lowerCase)) return "application/msword";
			if(".xml".equals(lowerCase)) return "text/xml";
		}
		return "text/html";
	}

	protected String toExtension(String contentType) {
		if (contentType != null) {
			String lowerCase = contentType.toLowerCase();
			if("image/bmp".equals(lowerCase)) return ".bmp";
			if("image/gif".equals(lowerCase)) return ".gif";
			if("image/jpeg".equals(lowerCase)) return ".jpg";
			if("image/png".equals(lowerCase)) return ".png";
			if("text/html".equals(lowerCase)) return ".html";
			if("text/plain".equals(lowerCase)) return ".txt";
			if("application/vnd.visio".equals(lowerCase)) return ".vsd";
			if("application/vnd.ms-powerpoint".equals(lowerCase)) return ".ppt";
			if("application/msword".equals(lowerCase)) return ".doc";
			if("text/xml".equals(lowerCase)) return ".xml";
		}
		return ".*";
	}
	
	protected String getFileExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public Long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(Long maxSize) {
		this.maxSize = maxSize;
	}

	
}
